package com.example.abe.diandi.trends.activity;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.example.BindView;
import com.example.OnClick;
import com.example.abe.diandi.R;
import com.example.abe.diandi.base.BaseActivity;
import com.example.abe.diandi.main.AppConfig;
import com.example.abe.diandi.nohttp.ApiUtil;
import com.example.abe.diandi.nohttp.CallServer;
import com.example.abe.diandi.nohttp.HttpListener;
import com.example.abe.diandi.trends.adapter.SearchTrendDelegate;
import com.example.abe.diandi.trends.model.SearchTrendListModel;
import com.example.abe.diandi.trends.model.TrendModel;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.yanzhenjie.nohttp.NoHttp;
import com.yanzhenjie.nohttp.RequestMethod;
import com.yanzhenjie.nohttp.rest.Request;
import com.yanzhenjie.nohttp.rest.Response;

import java.util.ArrayList;
import java.util.List;

import example.abe.com.framework.recycleview.adapter.BaseAdapter;
import example.abe.com.framework.refresh.OnLoadMoreListener;
import example.abe.com.framework.refresh.SwipeToLoadLayout;
import example.abe.com.framework.util.ToastUtil;

import static com.example.abe.diandi.nohttp.ApiUtil.METHOD;
import static com.example.abe.diandi.nohttp.ApiUtil.M_TREND_SEARCH_TREND;
import static com.example.abe.diandi.nohttp.ApiUtil.SERVICE;
import static com.example.abe.diandi.nohttp.ApiUtil.S_TREND;
import static com.yanzhenjie.nohttp.NoHttp.getContext;

public class SearchTrendActivity extends BaseActivity implements OnLoadMoreListener {

    @BindView(R.id.act_trends_search_et_search)
    protected EditText mEtSearch;

    @BindView(R.id.act_search_trend_swipe_to_load)
    protected SwipeToLoadLayout mSwipeToLoadLayout;

    @BindView(R.id.act_search_trend_tv_no_data_hint)
    protected TextView mTvNoData;

    @BindView(R.id.swipe_target)
    protected RecyclerView mRv;

    private List<TrendModel> mListData;

    private BaseAdapter<TrendModel> mAdapter;

    private LinearLayoutManager mLinearLayoutManager;

    private String mStrKey;

    private String mStartTrendId;

    @Override
    public int getLayoutID() {
        return R.layout.activity_search_trend;
    }

    @Override
    public void initData() {
        mListData = new ArrayList<>();
        mLinearLayoutManager = new LinearLayoutManager(getContext());
    }

    @Override
    public void initView() {
        mEtSearch.addTextChangedListener(mTextWatcher);
        mSwipeToLoadLayout.setOnLoadMoreListener(this);

        mAdapter = new BaseAdapter<>(getContext(), mListData);
        mAdapter.addItemViewDelegate(new SearchTrendDelegate());
        mRv.setLayoutManager(mLinearLayoutManager);
        mRv.setAdapter(mAdapter);

        mAdapter.setOnItemClickListener(onItemClickListener);

        mTvNoData.setVisibility(View.VISIBLE);
        mSwipeToLoadLayout.setVisibility(View.GONE);
    }

    @Override
    public void onLoadMore() {
        if (TextUtils.isEmpty(mStrKey)){
            ToastUtil.makeText("搜索内容为空");
            mSwipeToLoadLayout.setLoadingMore(false);
            return;
        }
        if (mListData.size() > 0){
            mStartTrendId = mListData.get(mListData.size()-1).getId();
        }else {
            mStartTrendId = "-1";
        }
        searchTrendList(mStartTrendId, mStrKey);
    }

    private BaseAdapter.OnItemClickListener onItemClickListener = new BaseAdapter.OnItemClickListener<TrendModel>() {
        @Override
        public void onItemClick(View view, RecyclerView.ViewHolder holder, TrendModel data, int position) {
            Intent intent = new Intent(SearchTrendActivity.this, TrendsShowActivity.class);
            intent.putExtra(TrendsShowActivity.NOTE_MODEL_DATA, mListData.get(position));
            startActivity(intent);
        }

        @Override
        public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, TrendModel data, int position) {
            return false;
        }
    };

    private TextWatcher mTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            mStrKey = mEtSearch.getText().toString();
        }
    };

    @OnClick(R.id.act_trends_search_tv_cancel)
    protected void onCancelClick(View v) {
        finish();
    }

    @OnClick(R.id.act_trends_search_iv_search)
    protected void onSearchClick(){
        if (TextUtils.isEmpty(mStrKey)) {
            ToastUtil.makeText("搜索内容为空");
        }
        mListData.clear();
        mStartTrendId = "-1";
        searchTrendList(mStartTrendId, mStrKey);
    }

    /**
     * 搜索内容
     * @param startTrendId 动态Id，加载更多时使用
     * @param key 关键字
     */
    private void searchTrendList(String startTrendId, String key){
        Request<String> request = NoHttp.createStringRequest(ApiUtil.URL, RequestMethod.POST);
        request.add(SERVICE, S_TREND)
                .add(METHOD, M_TREND_SEARCH_TREND)
                .add("userId", AppConfig.getUserModel().getId())
                .add("startTrendId", startTrendId)
                .add("key", key)
                .add("limit", 10);
        CallServer.getInstance().add(SearchTrendActivity.this, false, request, new HttpListener<String>() {

            @Override
            public void onSucceed(int what, Response<String> response) {
                JsonObject jsonObj = new JsonParser().parse(response.get()).getAsJsonObject();
                Boolean isSuccess = jsonObj.get("success").getAsBoolean();
                if (isSuccess) {
                    JsonObject data = jsonObj.getAsJsonObject("data");
                    SearchTrendListModel model = new Gson().fromJson(data, SearchTrendListModel.class);
                    mListData.addAll(model.getList());
                    mAdapter.notifyDataSetChanged();
                }
                mSwipeToLoadLayout.setLoadingMore(false);
                if (mListData.size() > 0){
                    mTvNoData.setVisibility(View.GONE);
                    mSwipeToLoadLayout.setVisibility(View.VISIBLE);
                }else {
                    mTvNoData.setVisibility(View.VISIBLE);
                    mSwipeToLoadLayout.setVisibility(View.GONE);
                }
            }

            @Override
            public void onFailed(int what, Response<String> response) {
                mSwipeToLoadLayout.setLoadingMore(false);
                ToastUtil.makeText("加载失败");
            }
        });
    }

}
